package com.tju.resource.server.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.ftp.Ftp;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tju.resource.common.ServiceException;
import com.tju.resource.mapper.DocContentMapper;
import com.tju.resource.mapper.DocUserPermMapper;
import com.tju.resource.model.DocContent;
import com.tju.resource.server.DocUserPermService;
import com.tju.resource.tool.result.Result;
import com.tju.resource.tool.result.ResultEnum;
import com.tju.resource.tool.result.ResultUtil;
import com.tju.resource.tool.tool.ChineseExceptionUtils;
import com.tju.resource.tool.tool.ClientParameters;
import com.tju.resource.tool.tool.Constants;
import com.tju.resource.tool.tool.EmptyUtils;
import com.tju.resource.yml_config.YmlConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import oshi.jna.platform.mac.SystemB;

import java.io.File;
import java.util.List;

/**
 * 文档实现
 *
 * @Author CLS
 * @Date 2022/2/28 11:27
 */
@Service
public class DocUserPermServiceImp implements DocUserPermService {

    @Autowired
    private DocContentMapper docContentMapper;
    @Autowired
    private YmlConfig ymlConfig;
    @Autowired
    private ChineseExceptionUtils zh_ch;
    @Autowired
    private DocContentMapper docMapper;
    @Autowired
    private BCryptPasswordEncoder bcrypt;

    /**
     * 查询指定文档
     *
     * @param logInName
     * @param parentMenu
     * @return
     */
    @Override
    public Result<Object> docData(String logInName, Object parentMenu) {
        try {
            List<DocContent> list = docContentMapper.selectDoc(logInName, parentMenu);
            return ResultUtil.success(ResultEnum.SUCCESS, list);
        } catch (Exception e) {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, e.getMessage());
        }
    }

    /*查询文档列表*/
    @Override
    public Result<Object> getComputerFile(ClientParameters parameters) {
        try {
            Page<DocContent> page = new Page<>(parameters.getPage(), parameters.getLimit());
            IPage<DocContent> iPage = docContentMapper.getPageUser(page, parameters);
            return ResultUtil.success(ResultEnum.SUCCESS, iPage.getRecords(), iPage.getTotal());
        } catch (Exception e) {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, e.getMessage());
        }
    }

    /*添加*/
    @Override
    @Transactional
    public Result<Object> addComputerFile(DocContent docContent, MultipartFile file) {
        //文件名
        String file_name = docContent.getImgName() + ".jpg";
        docContent.setImgName("['" + docContent.getImgName() + "']");
        try {
            if (!bcrypt.matches(Constants.RULE, ymlConfig.getFtpPass()))
                throw new ServiceException(zh_ch.ServerPasswordError);

            docMapper.insert(docContent);
            System.err.println(ymlConfig);
            Ftp ftp = new Ftp(ymlConfig.getFtpHost(), ymlConfig.getFtpPort(), ymlConfig.getFtpUser(), Constants.RULE);
            File dest = new File(ymlConfig.getResourceUrl() + file_name);
            file.transferTo(dest);
            ftp.upload("/nginx-1.20.1/html/static/mes/img/", dest);
            ftp.close();

            //1，上传文件
//            File dest = new File(ymlConfig.getResourceUrl() + file_name);
//            file.transferTo(dest);
            return ResultUtil.success(ResultEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(zh_ch.AddImage);
        }
    }

    /*修改*/
    @Override
    @Transactional
    public Result<Object> updComputerFile(DocContent docContent, MultipartFile file) {
        try {
            if (EmptyUtils.isNotEmpty(file)) {
                if (!bcrypt.matches(Constants.RULE, ymlConfig.getFtpPass()))
                    throw new ServiceException(zh_ch.ServerPasswordError);

                docMapper.insert(docContent);
                Ftp ftp = new Ftp(ymlConfig.getFtpHost(), ymlConfig.getFtpPort(), ymlConfig.getFtpUser(), Constants.RULE);
                File dest = new File(docContent.getImgName() + ".jpg");
                file.transferTo(dest);
                ftp.upload("/nginx-1.20.1/html/static/mes/img/", dest);
                ftp.close();

                //1，上传文件
//                File dest = new File(ymlConfig.getResourceUrl() + file_name);
//                file.transferTo(dest);
            }
            if (!docContent.getImgName().startsWith("["))
                docContent.setImgName("['" + docContent.getImgName() + "']");
            if (docContentMapper.updateById(docContent) > 0) {
                return ResultUtil.success(ResultEnum.SUCCESS);
            }
            throw new ServiceException(zh_ch.FailToEdit);
        } catch (Exception e) {
            throw new ServiceException(zh_ch.FailToEdit);
        }
    }

    /*删除*/
    @Override
    @Transactional
    public Result<Object> delComputerFile(DocContent docContent) {
        if (docContent.getImgName().startsWith("[")) {
            docContent.setImgName(docContent.getImgName().substring(2, docContent.getImgName().length() - 2));
        }
        try {
            FileUtil.del(ymlConfig.getResourceUrl() + docContent.getImgName().substring(2, docContent.getImgName().length() - 2) + ".jpg");
            if (docContentMapper.deleteById(docContent.getId()) > 0) {
                return ResultUtil.success(ResultEnum.SUCCESS);
            }
            throw new ServiceException(zh_ch.FailedToDelete);
        } catch (Exception e) {
            throw new ServiceException(zh_ch.FailedToDelete);
        }
    }
}
